import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Vector;



/* @Uses: Program To Implement baseline approach without Normalizetion
   1. Table Created: h5_score[Normalized]
   
   @SET
   1. score_table
   2. Stemmed or Not [This is stemmed]

*/
//
public class baseline_norm 
{
	 public Connection conn =  null;
	 public String dbname="2jboss";
	 public String userid="root";
	 public String passwd = "123";
	 public ArrayList<String> bugids =  null;
	 public String score_table = "h5_score";

	 
	 public void process(Connection conn)
	 {
		 System.out.println("I am in baseline");
		 bugids =  new ArrayList<String>();
		 String bug_q= "SELECT distinct bugid FROM bug_version where version in (select version from selected_version_for_4)";
		  	 
		 Statement stmt =  null;
		 ResultSet rs =  null;
		 
		 try
		  {
			  stmt = conn.createStatement();
		      stmt.execute(bug_q);
		      rs = stmt.getResultSet();
		    
		      while(rs.next())
		       {
			     String bugid =  rs.getString("bugid");
			     bugids.add(bugid);
			 
		       }//wh
		      
		      if(rs!=null)
		    	  rs.close();
		      if(stmt!=null)
		    	  stmt.close();
		 
		 } catch (SQLException e) 
		  { e.printStackTrace();	}
		 
		 //bugid, title, description, version
		 for(int i=0;i<bugids.size();i++)
		 {
			 System.out.println("count="+(i+1));
			 
			 String bugid = bugids.get(i);
			 String title = "";
			 String desc="";
			 String version="";
			 String td_q = "select * from bug_svn_info where bugid='"+bugid+"'";
			 String v_q = "select version from bug_version where bugid='"+bugid+"'";
			
			 try 
			  {
				 stmt=conn.createStatement();
				 stmt.execute(td_q);
				 rs = stmt.getResultSet();
				 while(rs.next())
				 	{
					 	title = rs.getString("summary");
					 	desc =  rs.getString("description");
				 	}
			 
				 stmt.execute(v_q);
				 rs=stmt.getResultSet();
				 
				 while(rs.next())
				 {
					 version = rs.getString("version");
					 boolean valid =isValidVesion(version,conn); 
					 if(valid)
					 {
						 break;
					 }
				 }//wh
			 
				 if(rs!=null)
						rs.close();
					 
				     if(stmt!=null)
					   stmt.close(); 
				 
			  }catch(SQLException e)
			  {
				  e.printStackTrace();
			  }
			  
			  System.out.println("bugid="+bugid+" version="+version);
			 // System.out.println("title="+title);
			 // System.out.println("desc="+desc);
			 
			  calculate_and_insert(bugid,title,desc,version);
		 }//for
		 	
		 try
		 {
		     if(rs!=null)
				rs.close();
			 
		     if(stmt!=null)
			   stmt.close();
		 
	 	} catch (SQLException e) 
	 	{ e.printStackTrace(); 	}

	 }//process
	 
	//calculate the ngram match between this bug report title and desc
	private void calculate_and_insert(String bugid, String title, String desc,String version)
	{

		Connection conn =  null;
		db_conn db =  new db_conn();
		conn =  db.connect(dbname, userid, passwd);
			 
		 String old_title = title;
		 String old_desc  = desc;
		 utility  u  =  new utility();
		 
		 general_fun gf =  new general_fun();
		// System.out.println("Title="+title+ " desc="+desc);
		 title = gf.clean(title);//not used
		 String title_camel = gf.do_camel_casing(title);// It Should be done Here otherwise next function will change it to lower cases()
		 title_camel = gf.remove_stop_words(title_camel);
		 title_camel = gf.remove_SW(title_camel);
	     title_camel = gf.apply_stemming(title_camel); //comment it  	
  		 
		 desc = gf.clean(desc);// not used
		 String desc_camel = gf.do_camel_casing(desc);//It should be done here otherwise Next function will change it to lower case()
		 desc_camel = gf.remove_stop_words(desc_camel);
		 desc_camel = gf.remove_SW(desc_camel);
		 desc_camel = gf.apply_stemming(desc_camel); // comment it
		 
		 System.out.println("Title="+title_camel+ " desc="+desc_camel);
		  
		 title_camel  = title_camel.toLowerCase();
		 desc_camel   =  desc_camel.toLowerCase();
		 
		 String title_camel_arr[] = title_camel.split("\\s+");
		 String desc_camel_arr[] = desc_camel.split("\\s+");
		 
		 Vector<ngram_and_frq> t_camel_unique =  u.cal_unique_ngram_with_frq(title_camel_arr);
		 Vector<ngram_and_frq> d_camel_unique =  u.cal_unique_ngram_with_frq(desc_camel_arr);
		 
		 		 
		 
		// ngram_match ng=  new ngram_match();
		 
		 file_extraction fe =  new file_extraction();
		 
		 String formated_version = formated_version(version);
		 System.out.println("version="+version+ "  formated(table)="+formated_version);
		 String table =  formated_version;
		 
		 Statement stmt = null;
		 String str_q= "select * from  " + table;
		 try 
		 {
			stmt =  conn.createStatement();
			stmt.execute(str_q);
			ResultSet  rs = stmt.getResultSet();
			
			ArrayList<td_fpath_object> td =  new ArrayList<td_fpath_object>();
		
			
			int count = 0;
			while(rs.next())
			 {
				System.out.println("count="+count++);
				String fid =rs.getString("file_id");
				String file_name = rs.getString("file_name");
				int file_no = rs.getInt("file_no");
				String file_path =rs.getString("file_path");
				//System.out.println("File Path="+file_path);
				
				
				file_name = file_name.replace(".java", "");
				String file_name_camel = gf.do_camel_casing(file_name);
				
				file_path=gf.remove_slash_and_file_name(file_path);
				file_path = file_path.replace(".java","");
				int first_space_index = file_path.indexOf(" ");
				file_path =  file_path.substring(first_space_index);// removing first String from the file path "JBOSS_AS_4_0_3"
				String file_path_camel = gf.do_camel_casing(file_path);
				
				
				file_name_camel=file_name_camel.toLowerCase();
				file_path_camel = file_path_camel.toLowerCase();
				
				file_name_camel = gf.apply_stemming(file_name_camel); //@2Comment it
				file_path_camel = gf.apply_stemming(file_path_camel); //@@ Comment it
				
				String file_name_camel_arr[]=file_name_camel.split("\\s+");
				String file_path_camel_arr[]=file_path_camel.split("\\s+");
				
				Vector<ngram_and_frq> file_camel_unique =u.cal_unique_ngram_with_frq(file_name_camel_arr);
				Vector<ngram_and_frq> path_camel_unique =u.cal_unique_ngram_with_frq(file_path_camel_arr);  
				
				//System.out.println("File Name(stemmed)="+file_name_camel +" Path(stemmed)="+file_path_camel);
				
				//intr();
				
				 //System.out.println("file  name="+file_name+" file_path="+file_path);
				
				 double tf_sim = camel_similarity(title_camel_arr, file_name_camel_arr);
				 double tpath_sim =camel_similarity(title_camel_arr, file_path_camel_arr);
				 double df_sim = camel_similarity(desc_camel_arr, file_name_camel_arr);
				 double dpath_sim=camel_similarity(desc_camel_arr, file_path_camel_arr);
				 
				 
				// System.out.println("tf_sim="+tf_sim+" tpath_sim="+tpath_sim+" df_sim="+df_sim+" dpath_sim="+dpath_sim);
					
					if(tf_sim!=0)
					{
					 tf_sim =  u.normalize(tf_sim,t_camel_unique,file_camel_unique);
					} 
					
					if(tpath_sim!=0)
					{
						tpath_sim = u.normalize(tpath_sim, t_camel_unique, path_camel_unique);
					}
					
					if(df_sim!=0)
					{
						df_sim = u.normalize(df_sim, d_camel_unique,file_camel_unique);
					}
					
					if(dpath_sim!=0)
					{
						dpath_sim = u.normalize(dpath_sim, d_camel_unique,path_camel_unique);
					}
					 
					//-------------Just To overcome range errors------------
					tf_sim = tf_sim*100;
					tpath_sim = tpath_sim*100;
					df_sim = df_sim*100;
					dpath_sim =dpath_sim*100;
					//-------------------------------------------------------
				 
					//System.out.println("tf_sim="+tf_sim+" tpath_sim="+tpath_sim+" df_sim="+df_sim+ " dpath_sim="+dpath_sim);
					
				  //intr();
				 td.add(new td_fpath_object(bugid,fid,table,title,desc,file_name,file_path,tf_sim,tpath_sim,df_sim,dpath_sim));
				  
				 
				 //d.add(new td_fpath_object(bugid,fid,table,desc,file_name,file_path,df_sim,dpath_sim));
				
				// insert_to_t_sim(bugid,fid,table,title,file_name,file_path,tf_sim,tpath_sim);//title
				 //insert_to_d_sim(bugid,fid,table,desc,file_name,file_path,df_sim,dpath_sim);//similarity
				// intr();
				
			 }//while
			
			if(rs!=null)
				rs.close();
			if(stmt!=null)
				stmt.close();
			
			gf.insert_to_td_sim(td,conn,score_table);  // @@ Not A comment
		
			if(conn!=null)
				conn.close();
			
			System.out.println("bugid="+bugid+ "  formated(table)="+formated_version);
		
			
		} catch (SQLException e) 
		{ 	e.printStackTrace(); }
		
	}//cal and insert
	
public double camel_similarity(String t_d_arr[], String f_p_arr[])
{
	//System.out.println("I am in camel");
	double sim = 0.0;
	for(int i=0;i<t_d_arr.length;i++)
	{
		 String a =  t_d_arr[i];
		 for(int j=0;j<f_p_arr.length;j++)
		 {
			 String b= f_p_arr[j];
			 
			 if(a.equalsIgnoreCase(b))
			 {
				 sim++;
				 //System.out.println("a="+a+" b="+b+ "  sim="+sim);
			 }
			 
		 }
	}
		
		
	return sim;	
}


public String formated_version(String version)
{
		 String formated_version="";

		 version =  version.toLowerCase();
		 version =  version.replace("jbossas-", "");
		 version =  version.replaceAll("final","").trim();	
		 version =  version.replaceAll("\\.", "_");
		 version = version.replaceAll("\\s+", "_");
		 
		// System.out.println("version = "+version); 
		 
		 int  i =-1;
		 int index= -1;
		 for(i=0;i<version.length();i++)
		  {
			 char a = version.charAt(i);
			 if(a=='_')
				 continue;
			 
			 else if(((a-'0')>=0)&&((a-'0')<=9))
			 {
				 index = i;
				 continue;
			 }
			 else
			 {
				 break;
			 }

		 }
		 
		 
		 //System.out.println("index="+index);
		 formated_version = version.substring(0, index+1);
		 formated_version =  formated_version.concat("_");
		 
		 //System.out.println("fm1="+formated_version);	 
		// System.out.println("v len="+version.length());
		 
		 if(index!=(version.length()-1))
		 {
		  formated_version =  formated_version.concat(version.substring(index+1));
		 }
		 
		 //System.out.println("fm="+formated_version);
		 formated_version =  formated_version.replaceAll("__", "_");
		 
		 if(formated_version.endsWith("_"))
		 {
			 int u_index = formated_version.lastIndexOf("_");
			 formated_version = formated_version.substring(0, u_index);
		 }	
			
			
	  return formated_version;
}

public boolean isValidVesion(String version, Connection conn) 
	{
	    Statement stmt =  null;
	    String v_q="select version from  selected_version_for_4";
	    Vector<String> selected_versions =  new Vector<String>();
	    
	    try
	     {
	    	stmt = conn.createStatement();
			stmt.execute(v_q);
			ResultSet rs =  stmt.getResultSet();
			
			while(rs.next())
			 {
			  selected_versions.add(rs.getString("version")); 	
			 }
			
			if(rs!=null)
				rs.close();
			if(stmt!=null)
				stmt.close();
		 } catch (SQLException e)
		 { 		e.printStackTrace(); 	}    
		 
		 //for
	     boolean flag =  false;
		 for(int i=0;i<selected_versions.size();i++)
		 {
			 if(version.equalsIgnoreCase(selected_versions.get(i)))
			 {
				  flag=  true;
			 }//if
		 }
		 
		return flag; 
		
}//isValidVesion


public void intr()
 {
		 BufferedReader br =  new BufferedReader(new InputStreamReader(System.in));
		 System.out.println("INTR");
		 try {
			br.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
 }
	 
	public static void main(String args[])
	{
			baseline_norm obj =  new baseline_norm();
			db_conn db=  new db_conn();
			obj.conn = db.connect(obj.dbname, obj.userid, obj.passwd);
			obj.process(obj.conn);
			db.close(obj.conn);
	     		
	 }//main


}
